<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>编辑模板</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
    <link rel="stylesheet" th:href="@{/pear/component/codemirror/css/codemirror.css}">
    <script th:src="@{/pear/component/layui/layui.js}"></script>
</head>
<body>
<input type="hidden" name="templateId" id="templateId" value="">
<input type="hidden" name="type" id="type" value="">
<input type="hidden" name="contentId" id="contentId" value="">
<form class="layui-form" action="">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item">
                <label class="layui-form-label">模板名</label>
                <div class="layui-input-block">
                    <input type="text" name="templateName" lay-verify="required|templateNameCheck" autocomplete="off"
                           placeholder="请输入模板名" maxlength="10" class="layui-input" id="templateName">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">模板路径</label>
                <div class="layui-input-block">
                    <input type="text" name="templateUrl" lay-verify="required|templateUrlCheck" autocomplete="off"
                           placeholder="请输入路径" maxlength="30" class="layui-input" id="templateUrl">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">模板类别</label>
                <div class="layui-input-block">
                    <select name="type" lay-verify="required" id="templateType">
                        <option value="">请选择模板类别</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">模板内容</label>
                <div class="layui-input-block">
                    <textarea id="codeEditor"></textarea>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-success layui-btn-sm" lay-submit=""
                    lay-filter="template-save">
                <i class="layui-icon layui-icon-ok"></i>
                保存修改
            </button>
            <button type="reset" class="layui-btn layui-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>

<script th:src="@{/pear/component/codemirror/css/codemirror.js}"></script>
<script th:src="@{/pear/component/codemirror/mode/javascript.js}"></script>
<script th:src="@{/pear/component/codemirror/addon/edit/closebrackets.js}"></script>
<script th:src="@{/pear/component/codemirror/addon/edit/matchbrackets.js}"></script>
<script th:src="@{/pear/component/codemirror/addon/hint/show-hint.js}"></script>
<script th:inline="javascript">
    window.onload = function () {
        const templateId = getTemplateIdFromUrl();
        const editor = CodeMirror.fromTextArea(document.getElementById("codeEditor"), {
            lineNumbers: true,
            mode: "javascript",
            theme: "default",
            matchBrackets: true,
            closeBrackets: true,
        });

        // 初始化 CodeMirror 编辑器
        layui.use(['form', 'jquery'], function () {
            let form = layui.form;
            let $ = layui.jquery;
            let baseURL = /*[[@{/}]]*/ '';

            form.verify({
                templateNameCheck: function (value) {
                    if (!new RegExp("^[a-zA-Z\u4e00-\u9fa5][a-zA-Z0-9\u4e00-\u9fa5]*$").test(value)) {
                        return '模板名称只能包含汉字、字母和数字，且不能以数字开头';
                    }
                },
                templateUrlCheck: function (value) {
                    if (!new RegExp("^[a-zA-Z0-9/]+\\.html$").test(value)) {
                        return '模板路径只能包含字母、数字和斜杠（/），且必须以 .html 结尾';
                    }
                }
            });


            // 加载模板类别
            $.ajax({
                url: baseURL + 'cms/template/getTypeList',
                method: 'GET',
                success: function (response) {
                    if (response.code === 1000) {
                        const types = response.data;
                        const $typeSelect = $('#templateType');
                        types.forEach(item => {
                            $typeSelect.append(`<option value="${item.templateTypeId}">${item.typeName}</option>`);
                        });
                        form.render('select'); // 渲染下拉框，确保选中项显示出来

                        // 第一个请求成功后执行第二个请求
                        if (templateId) {
                            $.ajax({
                                url: baseURL + 'cms/template/select/' + templateId,
                                method: 'GET',
                                success: function (response) {
                                    if (response.code === 1000) {
                                        const template = response.data;
                                        $('#templateName').val(template.templateName);
                                        $('#templateUrl').val(template.templateUrl);
                                        $('#templateType').val(template.type);
                                        // 解码并设置内容
                                        const decodedContent = decodeURIComponent((atob(template.content)));
                                        editor.setValue(decodedContent);
                                        $('#templateId').val(template.templateId);
                                        $('#contentId').val(template.contentId);
                                        form.render('select');
                                    } else {
                                        layer.msg('未获取到模板信息', {icon: 2});
                                    }
                                },
                                error: function () {
                                    layer.msg('请求失败', {icon: 2});
                                }
                            });
                        }

                    } else {
                        layer.msg('未获取到模板类别', {icon: 2});
                    }
                },
                error: function () {
                    layer.msg('请求失败', {icon: 2});
                }
            });

            // 表单提交逻辑
            form.on('submit(template-save)', function (data) {
                const templateContent = editor.getValue();
                if (!templateContent.trim()) {
                    layer.msg('模板内容不能为空', {icon: 2});
                    return false;
                }
                // 将内容转换为 Base64
                data.field.content = btoa(encodeURIComponent(templateContent)); // 将编码内容加到表单
                data.field.templateId = $('#templateId').val();
                data.field.contentId = $('#contentId').val();
                let loading = layer.msg('保存中...', {icon: 16, shade: 0.3, time: false});
                $.ajax({
                    url: baseURL + 'cms/template/update',
                    data: JSON.stringify(data.field),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        if (result.code === 1000) {
                            layer.msg(result.msg, {icon: 1, time: 2000}, function () {
                                parent.layer.close(parent.layer.getFrameIndex(window.name)); // 关闭当前页
                                parent.layui.table.reload("template-table"); // 刷新表格
                            });
                        } else {
                            layer.msg(result.msg, {icon: 2, time: 2000});
                        }
                    },
                    error: function (error) {
                        layer.close(loading);
                        let msg = error.responseJSON ? error.responseJSON.msg : error.responseText;
                        layer.msg(msg, {icon: 2});
                    }
                });

                return false; // 阻止默认提交
            });
        });

        function getTemplateIdFromUrl() {
            const urlParams = new URLSearchParams(window.location.search);
            const templateId = urlParams.get('templateId');
            return encodeURIComponent(templateId); // 对输入进行编码
        }
    };
</script>
</body>
</html>
